package sms.service.impl;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;
import sms.entity.Student_info;
import sms.service.StudentInfoService;

import java.util.ArrayList;
import java.util.List;

@Service
public class StudentInfoServiceImpl implements StudentInfoService {

    @Autowired
    private JdbcTemplate jdbcTemplate;

    @Override
    public void addStudentInfo(Student_info studentInfo) {
        String sql="inert into student_info(student_id, class_id, real_name,gender) values(?,?,? ,?)";
        jdbcTemplate.update(sql,studentInfo.getStudent_id(),studentInfo.getClass_id(),studentInfo.getReal_name(),studentInfo.getGender());
    }

    @Override
    public void editStudentInfo(Student_info studentInfo) {
        String sql="update student_info set class_id=?,real_name=?,gender=? where student_id=?";
        jdbcTemplate.update(sql,studentInfo.getClass_id(),studentInfo.getReal_name(),studentInfo.getGender(),studentInfo.getStudent_id());
    }

    @Override
    public List<Student_info> searchStudentInfo(String classId, String realName, String gender) {
        StringBuilder sql = new StringBuilder("SELECT * FROM student_info WHERE 1=1");
        List<Object> paramList = new ArrayList<>();

        if (classId != null && !classId.isEmpty()) {
            sql.append(" AND class_id = ?");
            paramList.add(classId);
        }

        if (realName != null && !realName.isEmpty()) {
            sql.append(" AND real_name LIKE ?");
            paramList.add("%" + realName + "%"); // 添加通配符
        }

        if (gender != null && !gender.isEmpty()) {
            sql.append(" AND gender = ?");
            paramList.add(gender);
        }

        return jdbcTemplate.query(sql.toString(), paramList.toArray(), (rs, rowNum) -> {
            Student_info studentInfo = new Student_info();
            studentInfo.setStudent_id(rs.getInt("student_id"));
            studentInfo.setClass_id(rs.getString("class_id"));
            studentInfo.setReal_name(rs.getString("real_name"));
            studentInfo.setGender(rs.getString("gender"));
            return studentInfo;
        });
    }
}